package handlers

import (
	"encoding/json"
	"gin-blog/cache"
	"gin-blog/models"
	"gin-blog/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UsersLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_login_Key := "login_error_" + username
	errorCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_Key).Int()
	if errorCount >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Srt(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_Key)
		if errorCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_Key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "密码错误3次",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func UsersList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var user []models.User

	redis_list_page_key := "list_page_" + strconv.Itoa(page)
	cachjson, _ := cache.Rdb.Get(cache.Ctx, redis_list_page_key).Result()
	if cachjson == "" {
		models.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list_page_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachjson), &user)
	}
	var count int64
	models.DB.Model(&models.User{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  user,
		"total": count,
		"msg":   "查询成功",
	})
	return
}
func UsersDetail(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	redis_detail_key := "detail_" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
